import { createRouter, createWebHistory } from "vue-router";

import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false });

// 静态导入需要用到的组件
import FilmList from "./pages/FilmList.vue";
import CinemaList from "./pages/CinemaList.vue";
import Center from "./pages/Center.vue";
import Login from "./pages/Login.vue";
import Home from "./pages/Home.vue";

import One from "./pages/FilmListOne.vue";
import Two from "./pages/FilmListTwo.vue";

const router = createRouter({
  history: createWebHistory(),

  // 设置路线，路由规则
  routes: [
    {
      path: "/",
      component: Home,
      redirect: "/films/one",
      children: [
        {
          path: "films", // /films
          component: FilmList,
          redirect: "/films/one",
          children: [
            {
              path: "one",
              component: One,
            },
            {
              path: "two",
              component: Two,
            },
          ],
        },
        {
          path: "cinemas", // /cinemas
          component: CinemaList,
        },
        {
          path: "center", // /center
          component: Center,
        },
      ],
    },
    {
      path: "/order",
      component: () => import("./pages/Order.vue"),
      meta: {
        title: "订单页面",
        needLogin: true,
      },
    },
    {
      path: "/money",
      component: () => import("./pages/Money.vue"),
      meta: {
        title: "钱包页面",
        needLogin: true,
      },
    },
    {
      path: "/login",
      component: Login,
      meta: {
        title: "登录页面",
      },
    },
  ],
});

// 配置需要登录之后才能访问的路由path集合
const needLogins = ["/order", "/money"];

router.beforeEach((to) => {
  NProgress.start();

  console.log("to", to);
  if (to.meta.needLogin) {
    const token = localStorage.getItem("token");

    if (!token) {
      return "/login?redirect=" + to.fullPath;
    }
  }

  // if (needLogins.includes(to.path)) {
  //   const token = localStorage.getItem("token");

  //   if (!token) {
  //     return "/login?redirect=" + to.fullPath;
  //   }
  // }
});

router.afterEach((to) => {
  NProgress.done();
  document.title = to.meta.title || "卖座网";
});

// 导出路由器
export default router;
